package com.ferry.config.client.util;

import com.ferry.config.client.annotation.FerryConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * Created by daiyong
 */
public class ReflectUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(ReflectUtil.class);

	public static Object transferValueTypePrimitively(Field field, String value) {
		Object result = null;
		String fieldName = field.getDeclaringClass().getName() + "." + field.getName();
		String typeName = field.getType().getSimpleName();
		try {
			if (StringUtils.equals(typeName, "String")) {
				result = value;
			} else if (StringUtils.equals(typeName, "int") || StringUtils.equals(typeName, "Integer")) {
				result = Integer.valueOf(value);
			} else if (StringUtils.equals(typeName, "long") || StringUtils.equals(typeName, "Long")) {
				result = Long.valueOf(value);
			} else if (StringUtils.equals(typeName, "float") || StringUtils.equals(typeName, "Float")) {
				result = Float.valueOf(value);
			} else if (StringUtils.equals(typeName, "double") || StringUtils.equals(typeName, "Double")) {
				result = Double.valueOf(value);
			} else if (StringUtils.equals(typeName, "boolean") || StringUtils.equals(typeName, "Boolean")) {
				result = Boolean.valueOf(value);
			} else {
				//ignore
			}
		} catch (Exception e) {
			LOGGER.error("transferValueTypePrimitively Exception, field:{}, value:{}", field, value, e);
		}
		return result;
	}

	private static Object transferValueTypeByMtConfigConverter(Field field, FerryConfig mtConfig, String value) {
		return transferValueTypePrimitively(field, value);
	}

	public static Object transferValueType(Field field, String value) {
		return transferValueTypePrimitively(field, value);
	}

}
